import base64
import glob
import os

from openai import OpenAI

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def encode_frames(frames_path):
    b64s = []
    # ls = os.listdir(frames_path)
    ls = glob.glob(f"{frames_path}*.jpg")
    for i in ls:
        with open(i, "rb") as image_file:
            b64 = base64.b64encode(image_file.read()).decode("utf-8")
        b64 = f"data:image/jpg;base64,{b64}"
        b64s.append(b64)
    return b64s


def test_video_understanding():

    def inference_with_api(
            save_frames_path,
            prompt,
            sys_prompt="You are a helpful assistant.",
            # model_id="qwen-vl-max-latest",
            model_id="qwen2.5-vl-72b-instruct",
    ):
        client = OpenAI(
            api_key='sk-38bdbf76aba641dfb1a671c7259d6dd5',
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
        bs64s = encode_frames(save_frames_path)
        messages = [
            {
                "role": "system",
                "content": [{"type": "text", "text": sys_prompt}]
            },
            {
                "role": "user",
                "content": [
                    # {"type": "video_url", "video_url": {"url": video_path}},
                    {"type": "video", "video": bs64s},
                    {"type": "text", "text": prompt},
                ]
            }
        ]
        completion = client.chat.completions.create(
            model=model_id,
            messages=messages,
        )
        print(completion)
        return completion.choices[0].message.content

    def get_video_frames_cv2(
                       video_path='/data1/xiancai/FACE_ANGLE_DATA/other/test/face_angle_test1.mp4',
                       save_path='/data1/xiancai/BABY_DATA/other/test/Video2DeepCam/res_10A4BE72856C_monitoringOff_1618593172930.mp4'
                       ):
        '''
        检测一个视频,保存检测结果
        :param video_path:
        :param save_path:
        :return:
        '''
        save_frames_path = f'{video_path}_frames/'
        if os.path.exists(save_frames_path):
            return save_frames_path
        import cv2
        # 设置video读入与写出
        cap = cv2.VideoCapture(video_path)
        fps, total = cap.get(cv2.CAP_PROP_FPS), int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  # 帧率，总帧数
        w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))  # 帧宽，帧高
        mp4 = cv2.VideoWriter_fourcc(*'mp4v')
        down_scale = 20  # 下采样
        res = cv2.VideoWriter(save_path, mp4, fps / down_scale, (w, h), True)  # WH
        numb = 0
        print(f'fps: {fps}, total: {total}, w: {w}, h: {h}')
        # 检测
        while (cap.isOpened()):
            numb += 1
            ret, frame = cap.read()
            if numb % down_scale == 0:
                if ret:
                    print(f'{numb}/{total},frame.shape:{frame.shape}')
                    # 缩小帧至 640x640
                    sc = 640 / max(frame.shape)
                    frame = cv2.resize(frame, dsize=(int(frame.shape[1] * sc), int(frame.shape[0] * sc)))

                    if True:
                        if not os.path.exists(save_frames_path):
                            os.makedirs(save_frames_path)
                        cv2.imwrite(f'{video_path}_frames/{str(numb).zfill(6)}.jpg', frame)

                else:
                    break

        cap.release()
        res.release()
        print('Done.')
        return save_frames_path

    # video_url = "https://duguang-labelling.oss-cn-shanghai.aliyuncs.com/qiansun/video_ocr/videos/50221078283.mp4"
    # video_url = r"D:\wechat_file\WeChat Files\wxid_ig5xjsfld7cp22\FileStorage\File\2025-04\1.mp4"
    video_url = r"D:\CODE\ZXC\hk-airport-poc\data\input\n3_q1_close_2.mp4"

    prompt = "描述视频内容，判断登机桥在何时靠接到飞机上"

    save_frames_path = get_video_frames_cv2(video_url)

    # response = inference(video_path, prompt)
    response = inference_with_api(save_frames_path, prompt)
    print(response)


if __name__ == '__main__':
    # test_()
    # test_spatial_understanding()
    test_video_understanding()